<template>
  <div class="withdraw-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-header">商家提现成功总金额</div>
        <div class="stat-amount">¥ {{ formatAmount(totalSuccessAmount) }}</div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form ref="queryRef" :model="queryParams" inline class="search-form">
        <el-form-item label="店铺名称">
          <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="待审核" />
            <el-option label="审核中" value="审核中" />
            <el-option label="到账成功" value="到账成功" />
            <el-option label="审核不通过" value="审核不通过" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="search-btn">
            搜索
          </el-button>
          <el-button @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-header">
        <div class="header-left">
          <span class="header-title">商家提现记录</span>
          <div class="header-tips">
            <el-tooltip content="待审核：等待平台审核" placement="top">
              <el-tag type="warning" size="small">待审核</el-tag>
            </el-tooltip>
            <el-tooltip content="审核中：正在审核处理" placement="top">
              <el-tag type="warning" size="small">审核中</el-tag>
            </el-tooltip>
            <el-tooltip content="到账成功：提现已完成" placement="top">
              <el-tag type="success" size="small">到账成功</el-tag>
            </el-tooltip>
            <el-tooltip content="审核不通过：提现被拒绝" placement="top">
              <el-tag type="danger" size="small">审核不通过</el-tag>
            </el-tooltip>
          </div>
        </div>
        <div class="header-stats">
          <span class="stat-item">
            总记录: <span class="total-text">{{ total }}</span>
          </span>
        </div>
      </div>
      
      <el-table 
        v-loading="loading" 
        :data="shopwithdrawList" 
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#fafafa', color: '#666', fontWeight: '500' }"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="店铺名称" align="center" prop="shopName" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            <div class="shop-name">
              <el-icon class="shop-icon"><Shop /></el-icon>
              {{ scope.row.shopName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="提现金额" align="center" prop="withdrawAmount" width="120">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text">¥{{ formatAmount(scope.row.withdrawAmount) }}</span>
              <small class="amount-label">申请金额</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实际到账金额" align="center" prop="actualAmount" width="130">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text success">¥{{ formatAmount(scope.row.actualAmount) }}</span>
              <small class="amount-label">到账金额</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平台服务费" align="center" prop="platformFee" width="110">
          <template #default="scope">
            <div class="amount-cell">
              <span class="fee-text">¥{{ formatAmount(scope.row.platformFee) }}</span>
              <small class="amount-label">服务费</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)" 
              :class="getStatusClass(scope.row.status)"
              size="small"
              effect="light"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核不通过原因" align="center" prop="rejectReason" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.rejectReason" class="reject-reason">{{ scope.row.rejectReason }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="submitTime" width="160">
          <template #default="scope">
            <div class="time-cell">
              <el-icon class="time-icon"><Clock /></el-icon>
              <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center" prop="processTime" width="160">
          <template #default="scope">
            <div class="time-cell" v-if="scope.row.processTime">
              <el-icon class="time-icon"><Check /></el-icon>
              <span>{{ parseTime(scope.row.processTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>


      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>


  </div>
</template>

<script setup name="Shopwithdraw">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { listShopwithdraw, getShopwithdraw, delShopwithdraw, addShopwithdraw, updateShopwithdraw } from "@/api/order/shopwithdraw"
import { parseTime } from '@/utils/ruoyi'
import { Shop, Clock, Check, Close } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const shopwithdrawList = ref([])
const loading = ref(true)
const total = ref(0)
const totalSuccessAmount = ref(0) // 商家提现成功总金额

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopName: null,
    status: null
  }
})

const { queryParams } = toRefs(data)

/** 查询商家提现记录列表 */
function getList() {
  loading.value = true
  listShopwithdraw(queryParams.value).then(response => {
    shopwithdrawList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 计算当前查询条件下的提现成功总金额
    calculateTotalSuccessAmount()
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
    
    // 如果API调用失败，使用模拟数据作为后备
    shopwithdrawList.value = [
      {
        id: 1,
        shopName: '诚小轩（商务学院店）',
        withdrawAmount: 60.00,
        actualAmount: 0.00, // 审核不通过，实际到账为0
        platformFee: 0.60,
        status: '审核不通过',
        rejectReason: '账户信息不匹配',
        submitTime: '2021-06-27T00:00:00',
        processTime: '2025-08-11T00:00:00'
      },
      {
        id: 2,
        shopName: '清行快递店（公山小区店）',
        withdrawAmount: 86.00,
        actualAmount: 85.14, // 86.00 - 0.86 = 85.14
        platformFee: 0.86,
        status: '到账成功',
        rejectReason: null,
        submitTime: '2020-10-20T00:00:00',
        processTime: '2020-10-20T00:00:00'
      },
      {
        id: 3,
        shopName: '诚小轩（商务学院店）',
        withdrawAmount: 21.00,
        actualAmount: 0.00, // 待审核，还未计算实际到账金额
        platformFee: 0.21,
        status: '待审核',
        rejectReason: null,
        submitTime: '2020-10-24T00:00:00',
        processTime: null
      },
      {
        id: 4,
        shopName: '清行快递店（公山小区店）',
        withdrawAmount: 31.00,
        actualAmount: 30.69, // 31.00 - 0.31 = 30.69
        platformFee: 0.31,
        status: '到账成功',
        rejectReason: null,
        submitTime: '2020-10-17T00:00:00',
        processTime: '2020-10-17T00:00:00'
      }
    ]
    total.value = 4
    calculateTotalSuccessAmount()
    
    proxy.$modal.msgError('数据加载失败，显示模拟数据')
  })
}

/** 计算提现成功总金额 */
function calculateTotalSuccessAmount() {
  try {
    let totalAmount = 0
    
    if (shopwithdrawList.value && Array.isArray(shopwithdrawList.value)) {
      shopwithdrawList.value.forEach(item => {
        if (item && item.status === '到账成功') {
          totalAmount += parseFloat(item.actualAmount || 0)
        }
      })
    }
    
    totalSuccessAmount.value = totalAmount
  } catch (error) {
    console.error('计算提现成功总金额失败:', error)
    totalSuccessAmount.value = 0
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.shopName = null
  queryParams.value.status = null
  queryParams.value.pageNum = 1
  getList()
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getList()
}

/** 当前页改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  getList()
}

// 移除了多选框相关的处理函数

/** 格式化金额显示 */
function formatAmount(amount) {
  return parseFloat(amount || 0).toFixed(2)
}

/** 计算实际到账金额 */
function calculateActualAmount(withdrawAmount, platformFee) {
  const withdraw = parseFloat(withdrawAmount || 0)
  const fee = parseFloat(platformFee || 0)
  return Math.max(0, withdraw - fee) // 确保不会出现负数
}

/** 获取状态类型 */
function getStatusType(status) {
  // 处理 null、undefined 或空值
  if (status == null || status === '') {
    return 'warning' // 默认为待审核样式
  }
  
  // 根据数据库ENUM值返回对应的标签类型
  if (status === '到账成功') {
    return 'success' // 到账成功 - 绿色
  } else if (status === '待审核' || status === '审核中') {
    return 'warning' // 待审核/审核中 - 橙色
  } else if (status === '审核不通过') {
    return 'danger' // 审核不通过 - 红色
  }
  
  return 'warning' // 未知状态默认为待审核样式
}

/** 获取状态文本 */
function getStatusText(status) {
  // 处理 null、undefined 或空值
  if (status == null || status === '') {
    return '待审核'
  }
  
  // 根据数据库ENUM值直接返回对应的显示文本
  if (status === '到账成功') {
    return '到账成功'
  } else if (status === '待审核') {
    return '待审核'
  } else if (status === '审核中') {
    return '审核中'
  } else if (status === '审核不通过') {
    return '审核不通过'
  }
  
  // 如果是未知状态，显示原值或默认为待审核
  return status || '待审核'
}

/** 获取状态样式类 */
function getStatusClass(status) {
  // 处理 null、undefined 或空值
  if (status == null || status === '') {
    return 'status-pending' // 默认为待审核样式
  }
  
  // 根据数据库ENUM值返回对应的样式类
  if (status === '到账成功') {
    return 'status-approved' // 到账成功
  } else if (status === '待审核' || status === '审核中') {
    return 'status-pending' // 待审核/审核中
  } else if (status === '审核不通过') {
    return 'status-rejected' // 审核不通过
  }
  
  return 'status-pending' // 默认样式
}

/** 审核通过操作 */
function handleApprove(row) {
  // 计算实际到账金额
  const actualAmount = calculateActualAmount(row.withdrawAmount, row.platformFee)
  
  const confirmMessage = `确认通过店铺"${row.shopName}"的提现申请吗？
申请金额：¥${formatAmount(row.withdrawAmount)}
平台服务费：¥${formatAmount(row.platformFee)}
实际到账金额：¥${formatAmount(actualAmount)}
通过后将直接标记为到账成功。`

  proxy.$modal.confirm(confirmMessage).then(() => {
    const updateData = {
      ...row,
      status: '到账成功',
      actualAmount: actualAmount, // 设置计算后的实际到账金额
      processTime: new Date().toISOString()
    }
    updateShopwithdraw(updateData).then(response => {
      proxy.$modal.msgSuccess(`审核通过成功！实际到账金额：¥${formatAmount(actualAmount)}`)
      getList()
    }).catch(error => {
      proxy.$modal.msgError("操作失败")
    })
  }).catch(() => {})
}

/** 审核拒绝操作 */
function handleReject(row) {
  proxy.$prompt(`请输入拒绝店铺"${row.shopName}"提现申请的原因：`, '审核拒绝', {
    confirmButtonText: '确定拒绝',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '拒绝原因不能为空',
    inputPlaceholder: '请详细说明拒绝原因...'
  }).then(({ value }) => {
    const updateData = {
      ...row,
      status: '审核不通过',
      rejectReason: value,
      actualAmount: 0, // 拒绝后实际到账金额为0
      processTime: new Date().toISOString()
    }
    updateShopwithdraw(updateData).then(response => {
      proxy.$modal.msgSuccess(`审核拒绝成功！拒绝原因：${value}`)
      getList()
    }).catch(error => {
      proxy.$modal.msgError("操作失败，请重试")
    })
  }).catch(() => {
    // 用户取消操作，不做任何处理
  })
}

// 页面初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.withdraw-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 8px;
  padding: 20px;
  color: white;
  width: 200px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.stat-header {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 200px;
}

.search-select {
  width: 150px;
}

.search-btn {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  color: white;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-tips {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stat-item {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-text {
  color: #1890ff;
  font-weight: bold;
}

/* 表格内容样式 */
.shop-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.shop-icon {
  color: #1890ff;
  font-size: 16px;
}

.amount-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.amount-text {
  color: #52c41a;
  font-weight: 600;
  font-size: 14px;
}

.amount-text.success {
  color: #52c41a;
}

.fee-text {
  color: #fa8c16;
  font-weight: 600;
  font-size: 14px;
}

.amount-label {
  color: #999;
  font-size: 10px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.time-icon {
  color: #999;
  font-size: 14px;
}

.reject-reason {
  color: #f56c6c;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

/* 表格操作按钮样式 */
.table-action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.table-action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
  min-width: 60px;
}

.table-action-buttons .el-button .el-icon {
  margin-right: 2px;
}

/* 状态标签自定义样式 */
:deep(.status-pending) {
  background-color: #fff7e6;
  border-color: #ffd591;
  color: #fa8c16;
}

:deep(.status-approved) {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

:deep(.status-rejected) {
  background-color: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
}

:deep(.status-completed) {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

:deep(.status-cancelled) {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #8c8c8c;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .stat-card {
    width: 100%;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #666;
  font-weight: 500;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-button--text) {
  padding: 0;
}
</style>